Fix issue where OrderInventory creates superfluous InventoryUnits #1751
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This fixes an issue where OrderInventory would miscount the number of existing inventory_units on a line item and create extra records.
InventoryUnits exist through the line_item.inventory_units, shipment.inventory_units, and order.inventory_units associations. Because of this, their associations can't be kept up to date in memory.
OrderInventory was counting inventory using inventory_units.size, which would return the in-memory count if the line_items.inventory_units association was loaded.
This issue was exposed by adding to the same line item multiple times without reloading the order. The line_item.inventory_units association would be become
loaded?
, because ActiveRecord's#size
marks a record as loaded if the count returns 0 (TIL!). On the next pass it would see the wrong size because the association was out of date, and add two inventory units instead of one.This avoids the issue by counting inventory using inventory_units.count, which doesn't consider the in-memory association.